package com.example.bluetoothclicker

import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.SeekBar
import android.widget.Switch
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.fragment.app.Fragment
import com.example.bluetoothclicker.home.BluetoothDeviceDialogFragment
import com.example.bluetoothclicker.normal.T9BluetoothManager


class HomeFragment : Fragment(R.layout.fragment_home) {

    private lateinit var bluetoothAdapter: BluetoothAdapter
    private lateinit var bluetoothStatusText: TextView
    private lateinit var bluetoothStatusIcon: ImageView
    private lateinit var scanDeviceButton: Button
    private lateinit var deviceCard: CardView
    private lateinit var deviceName: TextView
    private lateinit var deviceBattery: TextView
    private lateinit var lightSwitch:Switch
    private lateinit var colorCard:CardView
    private lateinit var brightCard:CardView
    private lateinit var colorValue:TextView
    private lateinit var colorSeekBar: SeekBar
    private lateinit var brightnessValue:TextView
    private lateinit var brightnessSeekBar: SeekBar
    private lateinit var sceneCard: LinearLayout


    private var connectedDeviceCount = 0
    private var bluetoothSwitch = false

    private val REQUEST_ENABLE_BT = 1

    // 广播接收器监听蓝牙连接状态和蓝牙开启/关闭状态
    private val bluetoothConnectionReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            when (action) {
                BluetoothAdapter.ACTION_STATE_CHANGED -> {
                    val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)
                    when (state) {
                        BluetoothAdapter.STATE_ON -> {
                            bluetoothStatusText.text = "蓝牙已开启"
                            bluetoothStatusIcon.setImageResource(R.drawable.ic_bluetooth_on)
                            bluetoothSwitch = true
                        }
                        BluetoothAdapter.STATE_OFF -> {
                            bluetoothStatusText.text = "蓝牙已关闭"
                            bluetoothStatusIcon.setImageResource(R.drawable.ic_bluetooth_off)
                            bluetoothSwitch = false
                            resetConnectedDeviceUI()
                        }
                    }
                }

            }
        }
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 初始化视图
        bluetoothStatusText = view.findViewById(R.id.bluetooth_status_text)
        bluetoothStatusIcon = view.findViewById(R.id.bluetooth_status_icon)
        scanDeviceButton = view.findViewById(R.id.scan_device_button)
        deviceCard = view.findViewById(R.id.device_card)
        deviceName = view.findViewById(R.id.device_name)
        deviceBattery = view.findViewById(R.id.device_battery)
        lightSwitch = view.findViewById(R.id.light_switch)
        colorCard = view.findViewById(R.id.device_color_card)
        brightCard= view.findViewById(R.id.device_bright_card)


        colorValue = view.findViewById(R.id.color_value)
        colorSeekBar = view.findViewById(R.id.colorSeekBar)
        brightnessValue = view.findViewById(R.id.brightness_value)
        brightnessSeekBar = view.findViewById(R.id.brightnessSeekBar)
        sceneCard =  view.findViewById(R.id.device_scene_card)


        // 初始化蓝牙适配器
        //val bluetoothManager = context?.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager?
        //bluetoothAdapter = bluetoothManager?.getAdapter()!!

       bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        // 设置蓝牙状态
        setupBluetooth()

        // 注册广播接收器
        val filter = IntentFilter().apply {
            addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
        }
        requireContext().registerReceiver(bluetoothConnectionReceiver, filter)

        T9BluetoothManager.setOnConnectionStateChangedListener_Home { device, isConnected ->
            if (isConnected) {
                // 设备已连接，更新设备信息和电量
                updateConnectedDevices()
            } else {
                resetConnectedDeviceUI()
            }
        }
        // 设置按钮点击事件，弹出设备扫描对话框
        scanDeviceButton.setOnClickListener {
            if (!bluetoothSwitch) {
                //如果没有开启手机蓝牙，就操作开启蓝牙
                openBlue(true)
            } else {
                BluetoothDeviceDialogFragment().show(childFragmentManager, "BluetoothDeviceDialogFragment")
            }
        }
        lightSwitch.setOnClickListener {
            if (lightSwitch.isChecked){
                //显示调参数面板
                brightCard.visibility = View.VISIBLE
                colorCard.visibility = View.VISIBLE
                sceneCard.visibility = View.VISIBLE
                //发送开灯命令。。。。。
                T9BluetoothManager.sendMessageToDevice("FA")
            } else{
                //隐藏调参数面板
                brightCard.visibility = View.INVISIBLE
                colorCard.visibility = View.INVISIBLE
                sceneCard.visibility = View.INVISIBLE
                //发送关灯命令。。。。。
                T9BluetoothManager.sendMessageToDevice("FB")
            }
        }
        //色温
        colorSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                // 处理进度变化事件
                colorValue.text = "  $progress%"
                //Toast.makeText(requireContext(), "进度: $progress", Toast.LENGTH_SHORT).show()
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                // 处理开始触摸事件
            }
            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                // 处理停止触摸事件
                //Toast.makeText(requireContext(), "进度: ${seekBar?.progress}", Toast.LENGTH_SHORT).show()
                //发送色温值。。。。。
                T9BluetoothManager.sendMessageToDevice("FB")
            }
        })
        //亮度
        brightnessSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                // 处理进度变化事件
                brightnessValue.text = "  $progress%"
                //Toast.makeText(requireContext(), "进度: $progress", Toast.LENGTH_SHORT).show()
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                // 处理开始触摸事件
            }
            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                // 处理停止触摸事件
                //Toast.makeText(requireContext(), "进度: ${seekBar?.progress}", Toast.LENGTH_SHORT).show()
                //发送亮度值。。。。。
                T9BluetoothManager.sendMessageToDevice("FB")
            }
        })
    }
    override fun onResume() {
        super.onResume()
        updateConnectedDevices()
    }
    override fun onDestroyView() {
        super.onDestroyView()
        // 注销广播接收器
        requireContext().unregisterReceiver(bluetoothConnectionReceiver)
    }

    // 设置蓝牙状态
    private fun setupBluetooth() {
        if (bluetoothAdapter == null) {
            bluetoothStatusText.text = "蓝牙不支持"
            bluetoothStatusIcon.setImageResource(R.drawable.ic_bluetooth_off)
        } else {
            if (!bluetoothAdapter.isEnabled) {
                bluetoothStatusText.text = "蓝牙已关闭"
                bluetoothStatusIcon.setImageResource(R.drawable.ic_bluetooth_off)
                bluetoothSwitch = false
                resetConnectedDeviceUI()
            } else {
                bluetoothStatusText.text = "蓝牙已开启"
                bluetoothStatusIcon.setImageResource(R.drawable.ic_bluetooth_on)
                bluetoothSwitch = true
            }
        }
    }
    //开启与关闭蓝牙
    private fun openBlue(isOpen: Boolean){
        if (isOpen) {
            enableBluetooth()
        } else {
            disableBluetooth()
        }
    }

    // 启用蓝牙
    private fun enableBluetooth() {
        if (!bluetoothAdapter.isEnabled) {
            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
        } else {
            Toast.makeText(requireContext(), "蓝牙已经开启", Toast.LENGTH_SHORT).show()
            scanDeviceButton.visibility = View.VISIBLE;
        }
    }

    // 禁用蓝牙
    private fun disableBluetooth() {
        if (bluetoothAdapter.isEnabled) {
            bluetoothAdapter.disable()  // 禁用蓝牙
            Toast.makeText(requireContext(), "蓝牙已关闭", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(requireContext(), "蓝牙已关闭", Toast.LENGTH_SHORT).show()
        }
        scanDeviceButton.visibility = View.INVISIBLE;
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == AppCompatActivity.RESULT_OK) {
                // 蓝牙成功启用
                Toast.makeText(requireContext(), "蓝牙已启用", Toast.LENGTH_SHORT).show()
                updateConnectedDevices()
            } else {
                // 蓝牙启用被拒绝
                Toast.makeText(requireContext(), "蓝牙启用被拒绝", Toast.LENGTH_SHORT).show()
                scanDeviceButton.visibility = View.INVISIBLE;
            }
        }
    }

    // 更新已连接设备 UI
    @SuppressLint("MissingPermission")
    private fun updateConnectedDevices() {
        val connectedDevices = T9BluetoothManager.getConnectedDevices()
        connectedDeviceCount = connectedDevices.size

        if (connectedDeviceCount > 0) {
            val firstDevice = connectedDevices[0]
            // 获取电量并更新 UI
            updateConnectedDeviceUI(firstDevice.name ?: "未知设备", firstDevice.address ?: "_/_")
            bluetoothStatusText.text = "蓝牙已连接 ($connectedDeviceCount)"
            bluetoothStatusIcon.setImageResource(R.drawable.ic_bluetooth_connected)

            T9BluetoothManager.connectToDevice(firstDevice)
            //读取参数
            T9BluetoothManager.getDeviceBatteryLevel(requireContext(), firstDevice) { batteryLevel ->
                requireActivity().runOnUiThread {
                    updateConnectedDeviceUI(firstDevice.name ?: "未知设备", firstDevice.address ?: "未知%")
                }
            }

        } else {
            resetConnectedDeviceUI()
            scanDeviceButton.visibility = View.VISIBLE;
            bluetoothStatusText.text = "蓝牙已开启"
            bluetoothStatusIcon.setImageResource(R.drawable.ic_bluetooth_on)
        }
    }


    // 更新已连接设备 UI
    private fun updateConnectedDeviceUI(name: String, mac: String) {
        deviceName.text = "设备名称：$name"
        deviceBattery.text = "Mac：$mac"
        lightSwitch.visibility= View.VISIBLE
        //显示调参数面板
        brightCard.visibility = View.VISIBLE
        colorCard.visibility = View.VISIBLE
        sceneCard.visibility = View.VISIBLE
    }

    // 重置设备卡片
    private fun resetConnectedDeviceUI() {
        deviceName.text = "设备名称：未连接"
        deviceBattery.text = "Mac：--"
        lightSwitch.visibility= View.INVISIBLE
        //隐藏调参数面板
        brightCard.visibility = View.INVISIBLE
        colorCard.visibility = View.INVISIBLE
        sceneCard.visibility = View.INVISIBLE

    }

    companion object {
        fun newInstance(): Fragment {
            return HomeFragment()
        }
    }
}